package cn.sylinx.hbatis.ext;

import java.util.HashMap;
import java.util.Map;

public abstract class AbstractDaoSingleton<T> implements DaoSupport<T> {

	protected Map<String, T> daoServiceMap = new HashMap<String, T>();

	public T getDaoService() {
		return getDaoService(getDefaultDatasourceName());
	}

	public T getDaoService(String datasourceName) {

		T daoService = daoServiceMap.get(datasourceName);
		if (daoService == null) {

			synchronized (datasourceName.intern()) {
				init(datasourceName);
			}

			daoService = daoServiceMap.get(datasourceName);
		}

		return daoService;
	}

	protected void init(String datasourceName) {
		T daoService = daoServiceMap.get(datasourceName);
		if (daoService == null) {
			daoService = createDaoService(datasourceName);
			daoServiceMap.put(datasourceName, daoService);
		}
	}

	protected abstract String getDefaultDatasourceName();

	protected abstract T createDaoService(String datasourceName);
}
